import { useState, useEffect, useCallback, useRef } from 'react'
import { useRouter, useLocation } from '@tanstack/react-router'
import { TabItem } from '../types'

// 递归查找路由
const findRoute = (routes: any[], path: string): any => {
  for (const route of routes) {
    if (route.path === path || route.fullPath === path) {
      return route
    }
    if (route.children) {
      const found = findRoute(route.children, path)
      if (found) {
        return found
      }
    }
  }
  return null
}

export const useTabManager = () => {
  const router = useRouter()
  const location = useLocation()
  
  const [tabs, setTabs] = useState<TabItem[]>([
    {
      key: '/',
      label: '首页',
      icon: null
    }
  ])
  const [activeTab, setActiveTab] = useState('/')
  
  // 使用ref来跟踪已经处理过的路径，避免重复处理
  const processedPaths = useRef<Set<string>>(new Set(['/']))

  // 处理标签页切换
  const handleTabChange = useCallback((key: string) => {
    setActiveTab(key)
    // 添加路由跳转逻辑
    router.navigate({ to: key })
  }, [router])

  // 根据路由变化更新标签页
  useEffect(() => {
    const currentPath = location.pathname
    
    // 如果这个路径已经处理过，直接更新激活状态
    if (processedPaths.current.has(currentPath)) {
      setActiveTab(currentPath)
      return
    }
    
    const existingTab = tabs.find(tab => tab.key === currentPath)
    
    // 如果标签页不存在，则添加新标签页
    if (!existingTab) {
      // 查找当前路由信息
      const route = findRoute([router.routeTree], currentPath)
      
      if (route) {
        const meta = route.options?.meta || {}
        const newTab: TabItem = {
          key: currentPath,
          label: meta.label || route.path || currentPath,
          icon: null // 图标可以在组件中处理
        }
        
        // 标记路径已处理
        processedPaths.current.add(currentPath)
        
        // 添加新标签页
        setTabs(prevTabs => {
          // 再次检查是否已存在，避免重复添加
          if (!prevTabs.some(tab => tab.key === currentPath)) {
            return [...prevTabs, newTab]
          }
          return prevTabs
        })
      }
    }
    
    // 更新激活的标签页
    setActiveTab(currentPath)
  }, [location.pathname, router.routeTree, tabs])

  // 处理标签页关闭
  const handleTabEdit = useCallback((targetKey: string | React.MouseEvent | React.KeyboardEvent, action: 'add' | 'remove') => {
    if (action === 'remove' && typeof targetKey === 'string') {
      // 首页标签页不能关闭
      if (targetKey === '/') {
        return
      }
      
      const newTabs = tabs.filter(tab => tab.key !== targetKey)
      
      // 如果没有标签页被移除，说明targetKey不匹配
      if (newTabs.length === tabs.length) {
        console.log('未找到要关闭的标签页:')
        console.log('  targetKey:', targetKey)
        console.log('  当前所有标签页keys:', tabs.map(tab => tab.key))
        return
      }
      
      // 从已处理路径集合中移除
      processedPaths.current.delete(targetKey)
      
      setTabs(newTabs)
      
      // 如果关闭的是当前激活的标签页，切换到第一个标签页
      if (targetKey === activeTab) {
        const firstTabKey = newTabs[0]?.key || '/'
        setActiveTab(firstTabKey)
        // 添加路由跳转逻辑
        router.navigate({ to: firstTabKey })
      }
    }
  }, [tabs, activeTab, router])

  return {
    tabs,
    activeTab,
    handleTabChange,
    handleTabEdit
  }
}